using System.Collections.Generic;
using Sirenix.OdinInspector;
using Sirenix.OdinInspector.Editor;
using Sirenix.Utilities;
using Sirenix.Utilities.Editor;
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;
using Pangoo.Common;
using System.Linq;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Information;
using JetBrains.Annotations;

namespace MetaTable.Editor
{
    public class MetaTableEditor : OdinMenuEditorWindow, IMetaTableEditor
    {
        [MenuItem("MetaTable/表格编辑器", false, 10)]
        private static void OpenWindow()
        {
            var window = GetWindow<MetaTableEditor>();
            window.position = GUIHelper.GetEditorWindowRect().AlignCenter(1100, 700);
            window.titleContent = new GUIContent("表格编辑器");
            window.MenuWidth = 250;
        }
        protected override void OnBeginDrawEditors()
        {
            if (MenuTree == null)
                return;

            var toolbarHeight = MenuTree.Config.SearchToolbarHeight;

            SirenixEditorGUI.BeginHorizontalToolbar(toolbarHeight);
            {
                // GUILayout.Label("提交拉取前务必点击保存全部配置");


                if (SirenixEditorGUI.ToolbarButton(new GUIContent("刷新菜单树")))
                {
                    ForceMenuTreeRebuild();
                }

                if (SirenixEditorGUI.ToolbarButton(new GUIContent("从")))
                {
                    var instance = MetaTableMainConfig.Instance;
                    Debug.Log(instance);
                }

            }
            SirenixEditorGUI.EndHorizontalToolbar();
        }


        public List<MetaTableConfig> GetMetatableConfigs()
        {
            return AssetDatabaseUtility.FindAsset<MetaTableConfig>().ToList();
        }


        // InitOverviewWrapper<AssetGroupOverviewWrapper, AssetGroupOverview, AssetGroupDetailRowWrapper, AssetGroupRowWrapper, AssetGroupNewRowWrapper, UnityAssetGroupRow>(m_OdinMenuTree, null, "资源组");


        public IMetaTableSingleOverviewWrapper BuildOverviewWrapper(string name, MetaTableConfig config)
        {
            if (name.IsNullOrWhiteSpace()) return null;

            var singleWrapper = ClassUtility.CreateInstance($"{name}SingleOverviewWrapper") as IMetaTableSingleOverviewWrapper;
            if (singleWrapper == null) return null;

            var overviewName = name + "Overview";
            singleWrapper.OverviewName = overviewName;
            singleWrapper.Config = config;

            var overview = AssetDatabaseUtility.FindScriptObject(overviewName, new string[] { config.PackageDir });
            if (overview.Count() > 0)
            {
                singleWrapper.Overview = overview.First() as IMetaTableOverview;
            }




            return singleWrapper as IMetaTableSingleOverviewWrapper;
        }

        [ShowInInspector]
        public List<IMetaTableSingleOverviewWrapper> overviewWrappers = new List<IMetaTableSingleOverviewWrapper>();

        public void BuildWrapper(OdinMenuTree tree)
        {
            overviewWrappers.Clear();
            var instance = MetaTableMainConfig.Instance;
            if (instance == null)
            {
                Debug.Log("MainConfig Instance is Null!");
                return;
            }
            tree.Add("主配置", instance);
            var configList = instance.MetaTableConfigs;
            if (configList == null) return;

            foreach (var config in configList)
            {
                if (config.Namespace.IsNullOrWhiteSpace()) continue;
                if (config.PackageDir.IsNullOrWhiteSpace()) continue;

                var list = new MetaTableConfigWrapper();
                list.Config = config;
                var treeName = config.Name.IsNullOrWhiteSpace() ? config.Namespace : config.Name;
                treeName = $"包配置-{treeName}";
                tree.Add(treeName, list);


                foreach (var d in config.Entries)
                {
                    switch (d.MetaTableType)
                    {
                        case MetaTableEntry.MetaTableTypeEnum.DefineRow:
                        case MetaTableEntry.MetaTableTypeEnum.ReferenceRow:
                            var className = d.ToClassName();
                            if (className.IsNullOrWhiteSpace()) continue;

                            var overviewWrapper = BuildOverviewWrapper(className, d.Config);
                            if (overviewWrapper != null)
                            {
                                list.Add(overviewWrapper);
                                overviewWrapper.MenuPath = treeName + "/" + d.ToCnName();
                                overviewWrapper.Tree = tree;
                                overviewWrapper.Editor = this;
                                overviewWrapper.Config = config;
                                tree.AddMenuItemAtPath(treeName, new OdinMenuItem(tree, d.ToCnName(), overviewWrapper));
                                overviewWrapper.Init();
                            }
                            break;
                    }
                }
            }

        }

        public class MetaTableConfigWrapper
        {
            [ReadOnly]
            public MetaTableConfig Config;

            [ShowInInspector]
            public List<MetaTableConfig> Dep => Config.ConfigDep;
            public List<IMetaTableSingleOverviewWrapper> wrappers = new List<IMetaTableSingleOverviewWrapper>();

            public void Add(IMetaTableSingleOverviewWrapper wrapper)
            {
                wrappers.Add(wrapper);
            }
        }



        protected override OdinMenuTree BuildMenuTree()
        {
            var tree = new OdinMenuTree(false);
            tree.Config.DrawSearchToolbar = true;
            tree.Config.AutoScrollOnSelectionChanged = false;

            BuildWrapper(tree);
            return tree;
        }

        Dictionary<string, object> DetailWrapperDict = new Dictionary<string, object>();

        Dictionary<string, object> RowWrapperDict = new Dictionary<string, object>();


        public void SetDetailWrapper(string uuid, object obj)
        {
            if (DetailWrapperDict.ContainsKey(uuid))
            {
                DetailWrapperDict[uuid] = obj;
            }
            else
            {
                DetailWrapperDict.Add(uuid, obj);
            }
        }

        public object GetDetailWrapper(string uuid)
        {
            if (DetailWrapperDict.TryGetValue(uuid, out object ret))
            {
                return ret;
            }
            return null;
        }

        public void SetRowWrapper(string uuid, object obj)
        {
            if (RowWrapperDict.ContainsKey(uuid))
            {
                RowWrapperDict[uuid] = obj;
            }
            else
            {
                RowWrapperDict.Add(uuid, obj);
            }
        }

        public object GetRowWrapper(string uuid)
        {
            if (RowWrapperDict.TryGetValue(uuid, out object ret))
            {
                return ret;
            }
            return null;
        }

        public void ShowDetail(string uuid)
        {
            var objectTarget = GetDetailWrapper(uuid);
            if (objectTarget != null)
            {
                TrySelectMenuItemWithObject(objectTarget);
            }
        }

        public void Refresh()
        {
            ForceMenuTreeRebuild();
        }
    }

}